package tjs.study.mini.mybatismini.config.proxy;

import org.springframework.beans.factory.FactoryBean;

import javax.sql.DataSource;
import java.lang.reflect.Proxy;

/**
 * Mapper的包装类，FactoryBean
 * 对标以下类
 *
 * @author nicky
 * @date 2021/9/6 上午11:19
 * @see org.mybatis.spring.mapper.MapperFactoryBean
 */
public class MapperFactoryBean<T> implements FactoryBean<T> {

    private Class<T> mapperInterface;
    private DataSource dataSource;

    public MapperFactoryBean(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @Override
    public T getObject() throws Exception {
        System.out.println("getObject开始生成代理...");
        MapperProxy mapperProxy = new MapperProxy(this.dataSource);
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}
